package com.shuyigou.servlet;


import com.shuyigou.mapper.CustomerMapper;
import com.shuyigou.pojo.Customer;
import com.shuyigou.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //1、获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //2、获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3、获取Mapper
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        //4、调用方法
        Customer customer = mapper.selectByUsernameAndPassword(username, password);
        //5、释放资源
        sqlSession.close();
        //6、判断是否登录成功
        //获取字符输出流，并设置content type
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //3. 判断user释放为null
        if(customer != null){
            // 登陆成功
            //1. 获取Session对象
            HttpSession session = req.getSession();
            //2. 存储数据
            session.setAttribute("username", customer.getUsername());
            session.setAttribute("customer_id", customer.getCustomer_id());
            resp.sendRedirect("./user_index.html");
        }else {
            // 登陆失败
            writer.write("登陆失败");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
